package com.bdqn.service.impl;

import com.bdqn.component.ArticleStatus;
import com.bdqn.component.BlogConstants;
import com.bdqn.dao.ImagesMapper;
import com.bdqn.entity.Images;
import com.bdqn.entity.User;
import com.bdqn.entity.UserWithBLOBs;
import com.bdqn.service.AlbumService;
import com.bdqn.util.FileResult;
import com.bdqn.util.FileUtil;
import com.bdqn.util.Page;
import com.bdqn.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.util.*;
import java.util.List;

/**
 * @Author SIMBA1949
 * @Date 2020/3/5 20:44
 */
@Service("albumService")
public class AlbumServiceImpl implements AlbumService {

    @Autowired
    private ImagesMapper imagesMapper;

    @Override
    public Result addUpdateAlbum(String blog, Images img, CommonsMultipartFile[] file, HttpServletRequest request) {
        int count = 0;
        List<FileResult> fileList = new ArrayList<FileResult>();
        if (Arrays.asList("add", "update").contains(blog)) {
            if (StringUtils.isBlank(img.getTitle()) || StringUtils.isBlank(img.getAddress())) {
                return Result.createError("参数错误");
            }
            if ("add".equals(blog)) {
                if (file == null || file.length == 0) {
                    return Result.createError("请选择图片后在提交");
                }
            }

            StringBuffer sb = new StringBuffer();
            if (file != null) {
                for (CommonsMultipartFile f : file) {
                    FileResult fs = FileUtil.saveFileToPath(request, f, BlogConstants.ALBUM_SAVE_PATH, BlogConstants.ALBUM_MAPPING_URL);
                    if (fs == null) {
                        deleteFiles(fileList, request);
                        return Result.createError("图片保存失败");
                    }
                    fileList.add(fs);
                    sb.append(fs.getHttpUrl() + ",");
                }
            }

            if ("add".equals(blog)) {
                img.setUrl(sb.toString());
            } else {
                img.setUrl(imagesMapper.selectByPrimaryKey(img.getUuid()).getUrl() + sb.toString());
            }
            img.setStatus(0);

            if ("add".equals(blog)) {
                img.setCreatetime(new Date());
                img.setUuid(UUID.randomUUID().toString().replace("-", "").toUpperCase());
                User loginUser = (User) request.getSession().getAttribute(BlogConstants.LOGIN_SESSION_KEY);
                img.setUserUuid(loginUser.getUuid());
                count = imagesMapper.insertSelective(img);
            } else {
                count = imagesMapper.updateByPrimaryKeySelective(img);
            }
            if (count == 0) {
                deleteFiles(fileList, request);
            }
        }
        if (count > 0) {
            return Result.createSuccess("操作成功");
        }

        return Result.createError("操作失败");
    }

    private void deleteFiles(List<FileResult> fileList, HttpServletRequest request) {
        if (fileList != null) {
            for (FileResult fileResult : fileList) {
                try {
                    FileUtil.deleteFile(request, fileResult.getFileName(), BlogConstants.ALBUM_SAVE_PATH);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
    }

    @Override
    public Page<Images> getPageAlbum(Boolean draft, String timeRangae,
                                     String title, Integer pageIndex, Integer pageSize, UserWithBLOBs user) {
        Page<Images> page = new Page<Images>(pageIndex, pageSize);
        Map<String, Object> param = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(title)) {
            param.put("title", title);
        }
        if (StringUtils.isNotBlank(timeRangae)) {
            param.put("startTime", timeRangae.split("~")[0].trim());
            param.put("endTime", timeRangae.split("~")[1].trim());
        }
        if (draft) {
            param.put("status", Arrays.asList(2));
        } else {
            param.put("status", ArticleStatus.getNotDraftStatus());
        }

        if (user != null) {
            if (StringUtils.isNotBlank(user.getUuid())){
                param.put("status",Arrays.asList(2));
            }else {
                param.put("status",ArticleStatus.getNotDraftStatus());
            }
        }
        page.setCount(imagesMapper.selectCount(param));
        param.put("start", (pageIndex - 1) * pageSize);
        param.put("row", pageSize);
        page.setDataList(imagesMapper.selectList(param));

        return page;
    }

    @Override
    public Images getAlbumById(String uuid) {
        return imagesMapper.selectByPrimaryKey(uuid);
    }

    @Override
    public Result deleteImg(String uuidImg, HttpServletRequest request) {
        if (StringUtils.isBlank(uuidImg)) {
            return Result.createError("参数错误");
        }

        Images img = imagesMapper.selectByPrimaryKey(uuidImg.split("-")[0]);
        img.setUrl(img.getUrl().replace(uuidImg.split("-")[1] + ",", ""));
        String fileName = uuidImg.split("")[1];
        fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        //删除文件
        if (FileUtil.deleteFile(request, fileName, BlogConstants.ALBUM_SAVE_PATH)) {
            if (imagesMapper.updateByPrimaryKeySelective(img) > 0) {
                return Result.createSuccess("删除成功");
            }
        }
        return Result.createError("删除失败");
    }

    @Override
    public Result updateCover(String uuid, CommonsMultipartFile file, HttpServletRequest request) {
        if (StringUtils.isBlank(uuid)) {
            return Result.createError("参数错误");
        }
        FileResult fs = FileUtil.saveFileToPath(request, file, BlogConstants.ALBUM_SAVE_PATH, BlogConstants.ALBUM_MAPPING_URL);
        String fileName = "";
        if (fs != null) {
            Images img = imagesMapper.selectByPrimaryKey(uuid);
            String urls[] = img.getImgUrl();
            fileName = urls[urls.length - 1];
            urls[urls.length - 1] = fs.getHttpUrl();
            StringBuffer sb = new StringBuffer();
            for (String str : urls) {
                if (StringUtils.isNotBlank(str)) {
                    sb.append(str + ",");
                }
                img.setUrl(sb.toString());
                fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
                //删除文件
                if (FileUtil.deleteFile(request, fileName, BlogConstants.ALBUM_SAVE_PATH)) {
                    if (imagesMapper.updateByPrimaryKeySelective(img) > 0) {
                        return Result.createSuccess(fs.getHttpUrl(), "更换成功");
                    }
                }
            }
        }

        return Result.createError("更换失败");
    }

    @Override
    public Result updateStatus(String flag, String uuid, HttpServletRequest request) {
        if (StringUtils.isBlank(uuid) || !Arrays.asList("draft", "return", "delete", "send", "cancel").contains(flag)) {
            return Result.createError("参数错误");
        }

        Images img = imagesMapper.selectByPrimaryKey(uuid.trim());

        if ("delete".equals(flag)) {
            String urls[] = img.getImgUrl();
            if (imagesMapper.deleteByPrimaryKey(uuid) > 0) {
                for (String fileName : urls) {
                    try {
                        String fname = fileName.substring(fileName.lastIndexOf("/") + 1);
                        FileUtil.deleteFile(request, fname, BlogConstants.ALBUM_SAVE_PATH);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }

                }
                return Result.createSuccess("删除成功");
            }
        } else {
            Map<String, Integer> map = new HashMap<String, Integer>();
            map.put("draft", ArticleStatus.DRAFTS.getValue());
            map.put("return", ArticleStatus.AVAILABLR.getValue());
            map.put("send", ArticleStatus.AVAILABLR.getValue());
            map.put("cancel", ArticleStatus.DISABLR.getValue());
            img.setStatus(map.get(flag));
            System.out.println(img.getImgUrl().toString());
            if (imagesMapper.updateByPrimaryKeySelective(img) > 0) {
                return Result.createSuccess("操作成功");
            }
        }
        return Result.createError("操作失败");
    }


}
